package com.ourhours.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ourhours.message.common.RedisKey;
import com.ourhours.message.domain.Template;
import com.ourhours.message.enums.SmsTypeEnum;
import com.ourhours.message.mapper.TemplateMapper;
import com.ourhours.message.service.TemplateService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chi.chen
 * @since 2018-03-20
 */
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {


    private static final Logger LOGGER = LoggerFactory.getLogger(EmailSendServiceImpl.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void initTemplates(Long vendorId) {
        Template entityForWrapper = new Template();
        entityForWrapper.setDeleted(0L);
        entityForWrapper.setVendorId(vendorId);
        EntityWrapper<Template> wrapper = new EntityWrapper<>(entityForWrapper);
        // 当前商户的已有模板
        List<Template> currList = this.selectList(wrapper);
        Map<String, Template> currMap = new HashedMap();
        // 模板的默认模板，是指vendorId=0的数据。当修改了是vendorId=0的数据，默认模板也被修改
        List<Template> defaultList = new ArrayList<>();
        Map<String, Template> defaultMap = new HashedMap();
        // 当前商户的已有模板 转存到map
        if (currList != null && currList.size() > 0) {//可以改成拉姆大表达式
            for (Template item : currList) {
                currMap.put(item.getSmsType(), item);
            }
        }
        // 模板的默认模板 转存到map
        if (vendorId > 0L) {//可以改成拉姆大表达式
            Template entityForWrapper0 = new Template();
            entityForWrapper0.setDeleted(0L);
            entityForWrapper0.setVendorId(0L);
            EntityWrapper<Template> wrapper0 = new EntityWrapper<>(entityForWrapper0);
            defaultList = this.selectList(wrapper0);
            if (defaultList != null && defaultList.size() > 0) {
                for (Template item : defaultList) {
                    defaultMap.put(item.getSmsType(), item);
                }
            }
        }
        else{
            defaultMap = currMap;
        }
        // 遍历枚举values，以其为标杆。检查当前商户的已有模板是否都存在
        for (SmsTypeEnum item : SmsTypeEnum.values()) {
            boolean isExist = currMap.get(String.valueOf(item.getCode())) == null ? false : true;
            if (!isExist) {
                Template entity = new Template();
                entity.setVendorId(vendorId);
                entity.setDeleted(0L);
                entity.setSysVersion(1);
                entity.setCreateUser("System");
                entity.setUpdateUser("System");
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                entity.setSmsType(String.valueOf(item.getCode()));
                if (vendorId == 0L){
                    entity.setContent(item.getContent());
                    LOGGER.info("新添加模板成功参数：{}",vendorId);
                }
                else if (defaultMap.get(String.valueOf(item.getCode())) == null){
                    entity.setContent(item.getContent());
                }
                else {
                    entity.setContent(defaultMap.get(String.valueOf(item.getCode())).getContent());
                }
                this.insert(entity);
            }
        }
    }

    public Template getTemplateById(Long id) {
        String cacheValue = stringRedisTemplate.opsForValue().get(RedisKey.MESSAGE_TEMPLATE_INFO_BY_ID.getKey() + id);
        Template entity;
        if (StringUtils.isBlank(cacheValue)) {
            entity = this.selectById(id);
            this.setTemplateByIdCache(entity);
        } else {
            entity = JSON.parseObject(cacheValue, Template.class);
        }
        return entity;
    }

    public void setTemplateByIdCache(Template entity) {
        stringRedisTemplate.opsForValue().set(RedisKey.MESSAGE_TEMPLATE_INFO_BY_ID.getKey() + entity.getId(), JSON.toJSONString(entity), RedisKey.MESSAGE_TEMPLATE_INFO_BY_ID.getTerm(), TimeUnit.SECONDS);
    }

    public Template getTemplateByType(int smsType, Long vendorId) {
        String cacheValue = stringRedisTemplate.opsForValue().get(RedisKey.MESSAGE_TEMPLATE_INFO_BY_TYPE.getKey() + vendorId + "_" + smsType);
        Template entity;
        if (StringUtils.isBlank(cacheValue)) {
            EntityWrapper<Template> wrapper = new EntityWrapper();
            wrapper.eq("sms_type", String.valueOf(smsType));
            wrapper.eq("vendor_id", vendorId);
            wrapper.eq("deleted", 0L);
            entity = this.selectOne(wrapper);
            LOGGER.info("获取模板的entity，参数:{},{},结果:{}", smsType, vendorId, entity);
            if (entity == null || entity.getId() == null) {
                this.initTemplates(vendorId);
                entity = this.selectOne(wrapper);
            }


            this.setTemplateByTypeCache(entity);
        } else {
            entity = JSON.parseObject(cacheValue, Template.class);
        }
        return entity;
    }

    public void setTemplateByTypeCache(Template entity) {
        stringRedisTemplate.opsForValue().set(RedisKey.MESSAGE_TEMPLATE_INFO_BY_TYPE.getKey() + entity.getVendorId() + "_" + entity.getSmsType(), JSON.toJSONString(entity), RedisKey.MESSAGE_TEMPLATE_INFO_BY_TYPE.getTerm(), TimeUnit.SECONDS);
    }
}